package helper

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
)

// 常用目录
const (
	PathUploads = "uploads"
)

var paths = []string{
	PathUploads,
}

// InitPaths 创建文件路径
func InitPaths() {
	for _, one := range paths {
		Mkdirs(one)
	}
}

// BuildUploadPathWithSlash 构造上传文件路径
func BuildUploadPathWithSlash(filename string) string {
	return fmt.Sprintf("%s/%s", PathUploads, filename)
}

// BuildUploadPathWithNone 构造上传文件路径
func BuildUploadPathWithNone(filename string) string {
	return fmt.Sprintf("%s%s", PathUploads, filename)
}

// BuildUploadPathWithAny 构造上传文件路径
func BuildUploadPathWithAny(filename string, sign string) string {
	return fmt.Sprintf("%s%s%s", PathUploads, sign, filename)
}

// IsPathExists 文件是否存在
func IsPathExists(path string) bool {
	_, err := os.Stat(path)
	return (err == nil)
}

// Mkdirs 创建文件目录
func Mkdirs(path string) bool {
	dir, _ := filepath.Split(path)
	if len(dir) > 0 {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return false
		}
	}
	return true
}

// DeleteLocalFile 删除本地文件
func DeleteLocalFile(localPath string) error {
	return os.Remove(localPath)
}

// RemoveAll 删除目录
func RemoveAll(localPath string) error {
	return os.RemoveAll(localPath)
}

// WriteFileWithIoutil 写数据到文件
func WriteFileWithIoutil(name, content string) (err error) {
	if len(name) > 0 && len(content) > 0 {
		if Mkdirs(name) {
			err = ioutil.WriteFile(name, []byte(content), 0644)
		}
	}
	return
}
